package com.qf.shopemail.listener;

import com.qf.common.constant.RabbitMqConstants;
import com.qf.entity.Email;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

@Component
public class EmailQueueListener {
    @Value("${spring.mail.username}")
    private String fromUser;
    @Autowired
    private JavaMailSender javaMailSender;

    @RabbitListener(queues = RabbitMqConstants.EMAIL_QUEUE)
    public void sendEmail(Email email, Channel channel, Message message) {
        System.out.println("email的消息===============================》" + email);
        try {
            //javaMailSender
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //封装
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            if (!StringUtils.isEmpty(email.getCcUser())) {
                mimeMessageHelper.setCc(email.getCcUser());
            }
            mimeMessageHelper.setFrom(fromUser);
            mimeMessageHelper.setSubject(email.getTitle());
            mimeMessageHelper.setText(email.getContent());
            mimeMessageHelper.setTo(email.getToUser());

//            javaMailSender.send(mimeMessage);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}
